package com.zhongxi.guoyuan.fragment.collectfragment;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.CollectionAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseFragment;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.user.center.CollectionData;
import com.zhongxi.guoyuan.entity.user.center.CollectionResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.view.beautifulStore.ProjectDetailActivity;
import com.zhongxi.guoyuan.view.rewardCoin.RewardCoinDetailActivity;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * A simple {@link Fragment} subclass.
 */
public class CollectBeautyFragment extends BaseFragment implements AdapterView.OnItemClickListener, PullToRefreshBase.OnRefreshListener2<ListView> {


    @Bind(R.id.lvList)
    PullToRefreshListView lvList;

    private List<CollectionData> data = new ArrayList<>();
    private int type = 1;
    private CollectionAdapter adapter;
    private CollectionResult result;
    private Map<String, String> map = new HashMap<>();
    private String flag;
    private int pos;


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            pos = (int) msg.obj;

            deleteItem();
        }
    };

    private void deleteItem() {
        flag = "del";
        map.put("ftype", data.get(pos).getFtype() + "");
        map.put("fid", data.get(pos).getId());
        getServer(Url.DEL_FAVORITE, map, "", false, null, "post");
    }

    private JSONObject jsonExt;
    private JSONObject jsonObject;

    public CollectBeautyFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_collect_beauty, container, false);
        return view;
    }

    @Override
    protected void initView() {
        super.initView();
        lvList= (PullToRefreshListView) getView().findViewById(R.id.lvList);
        lvList.setMode(PullToRefreshBase.Mode.BOTH);  //支持上拉和下拉加载更多
    }

    @Override
    protected void initData() {
        super.initData();
        getCollectionData();
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        lvList.setOnRefreshListener(this);
        lvList.setOnItemClickListener(this);
    }

    private void getCollectionData() {
        flag = "list";
        String str = "&ftype=" + type + "&page=" + pageNum;
        getServer(Url.MY_FAVORITE_LIST, null, str, false, null, "get");
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        try {
            if ("list".equals(flag)) {
                result = gson.fromJson(response, CollectionResult.class);
                MyApplication.getInstance().setSpValue(result.getSafeobj());
                if (pageNum == 1) {
                    data.clear();
                }
                if (result.getFavorite().size() > 0) {
                    data.addAll(result.getFavorite());
                }

                jsonObject = new JSONObject(response);
                jsonExt = jsonObject.optJSONObject("ext");

                if (result.getFavorite().size()>0){

                    adapter = new CollectionAdapter(context, data, jsonExt, handler);
                    lvList.setAdapter(adapter);
                }
                lvList.onRefreshComplete();
            } else if ("del".equals(flag)) {
                BaseResponse result = gson.fromJson(response, BaseResponse.class);
                MyApplication.getInstance().setSpValue(result.getSafeobj());
                data.remove(pos);
                adapter.notifyDataSetChanged();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        try {
            BaseResponse result = gson.fromJson(response, BaseResponse.class);
            if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
                MyApplication.getInstance().setSpValue(result.getSafeobj());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        pageNum = 1;
        getCollectionData();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        pageNum++;
        getCollectionData();
    }


    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        lvList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent();
                JSONObject jsonRefid = jsonExt.optJSONObject(data.get(position - 1).getRefid());
                if (null != jsonRefid && !"".equals(jsonRefid)) {
                    if (null != jsonRefid.optString("status") && !"".equals(jsonRefid.optString("status"))) {

                        //跳转到美豆项目页面
                        intent.setClass(context, ProjectDetailActivity.class);
                        intent.putExtra("id", jsonRefid.optString("id"));
                        startActivity(intent);

                    }
                } else {
                    showShortToast("商品已下架，建议您移除该商品");
                }

            }
        });
    }
}
